defmodule IocpMonitor.HTTPServer do
  use Raxx.SimpleServer
  use Ace.HTTP.Service, [cleartext: true]

  alias IocpMonitor.Worker.DataBuffer

  @impl Raxx.SimpleServer
  def handle_request(%{method: :GET, path: [device_address]}, _state) do
    if device_address =~ ~r/^\d+$/ do
      String.to_integer(device_address)
      |> handle_query()
    else
      response(:not_found)
    end
  end

  def handle_request(_, _state) do
    response(:not_found)
  end

  defp handle_query(device_address) when is_integer(device_address) do
    case DataBuffer.peek(device_address) do
      {:ok, data} ->
        body = Poison.encode!(data)
        response(:ok)
        |> set_header("content-type", "application/json; charset=utf-8")
        |> set_body(body)
      :empty ->
        response(:not_found)
    end
  end
end
